﻿#region Imports Directives

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Quartz;
using log4net;
using ScenarioFramework.WorkflowEngine.Scheduler.Data;
using ScenarioFramework.WorkflowEngine.DataBase;


#endregion

namespace ScenarioFramework.WorkflowEngine.Scheduler.Jobs
{
    public class ListenerJob : Quartz.IJob
    {
        #region Variables
        private static ILog _log = LogManager.GetLogger(typeof(ListenerJob));

       
        #endregion

        #region Constructor

        public ListenerJob()
        {
        }

        #endregion

        void Quartz.IJob.Execute(Quartz.JobExecutionContext context)
        {
            bool bJobRunning  = JobController.Instance().AddJob(context.JobDetail.Name);
            if ( !bJobRunning)
                return;
            
            IList items = Helpers.ExchangeItem().SelectItemToWork();
            IEnumerator enumerator = items.GetEnumerator();
            enumerator.Reset();
            while ( enumerator.MoveNext () )
            {
                ExchangeItem item = (ExchangeItem)enumerator.Current;

                ScenarioFramework.WorkflowEngine.Events.EventBase _event = 
                    ScenarioFramework.WorkflowEngine.Events.EventsFactory.MakeEvent(item.Object);

                Trigger trigger = _event.GetTrigger(item.ProcessXML);
                trigger.Name = String.Format("Trigger_{0}", item.Id);

                JobDetail jobDetail = _event.GetJobDetail(item.ProcessXML);
                jobDetail.Name= String.Format("Activity_{0}", item.Id);

                try
                {
                    context.Scheduler.ScheduleJob(jobDetail, trigger);
                    Helpers.ExchangeItem().MarkAsWorked(item.Id);
                }
                catch (Exception err)
                {
                    System.Console.Error.WriteLine(err.Message);
                }
            }

            JobController.Instance().RemoveJob(context.JobDetail.Name);

        }
    }
}
